package com.bigfreakindeals.Activities;


import java.lang.annotation.Retention;
import java.util.ArrayList;  

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Protocols.SoapHandlers.PayPalWebHandler;
import com.paypal.android.MEP.PayPalActivity;

import android.app.Activity;
 import android.app.ActivityGroup;  
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;  
import android.content.res.Configuration;
import android.graphics.AvoidXfermode;
import android.os.Bundle;  
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;  
import android.view.MenuInflater;  
import android.view.MenuItem;  
import android.view.View;  


public class ActiveDealsActivityGroup extends ActivityGroup {  

	         // Keep this in a static variable to make it accessible for all the nesten activities, lets them manipulate the view  
public static ActiveDealsActivityGroup activedealsgroup;  
   
         // Need to keep track of the history if you want the back-button to work properly, don't use this if your activities requires a lot of memory.  

    public View view = null;
     @Override  
     protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           ApplicationEx.getInstance().history = new ArrayList<View>();  
           activedealsgroup = this;  
     		
           if (ApplicationEx.getInstance().nodeasIntent!=null){
    		   view = getLocalActivityManager().startActivity("NoActiveDeals",ApplicationEx.getInstance().nodeasIntent
                      .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
                       .getDecorView();  
    		 
    		   view.setId(Constant.ID_NOACTIVEDEALS);
    		   // Replace the view of this ActivityGroup  
    		   replaceView(view);

    		   
    		ApplicationEx.getInstance().nodeasIntent = null;
    		   
    	   }else if (view == null){
    		   
        	   view = getLocalActivityManager().startActivity("ActiveDeals", new  
                                             Intent(this,ActiveDealsActivity.class)  
                                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
                                             .getDecorView();  
        	   view.setId(Constant.ID_ACTIVEDEALS);
               // Replace the view of this ActivityGroup  
        	   replaceView(view);
           }
           
        }  
     
    private void paypalDone(boolean viewCoupons){
    	
    
    	
    	if (viewCoupons)
         {	ApplicationEx.getInstance().currentTab = 1;
        	 Intent intent = new Intent(Constant.EVENTS_UPDATECURRENTTAB);
			 ApplicationEx.getInstance().sendBroadcast(intent);

         }
    	
    }
   @Override
   public void onResume(){
	    // Start the root activity withing the group and get its view  
	  System.out.println("ONRESUME@ActiveDealsGroup"+ApplicationEx.getInstance().history.size());
		 
	  
	  View v =  ApplicationEx.getInstance().history.get(ApplicationEx.getInstance().history.size()-1);
      setContentView(v);
      super.onResume();
 	   

   }
   
   @Override
	 public void onConfigurationChanged(Configuration newConfig) {
	 super.onConfigurationChanged(newConfig);
	 System.out.println("onconfigchange@ACTVEDEALSGROUP");
	 }

     public void replaceView(View v) {  
    	
    	 
    	 //check if the page already exist
    	 
    	 // Adds the old one to history  
    	 // Changes this Groups View to the new View.  
    	 
         for (int i = 0; i<ApplicationEx.getInstance().history.size();i++){
         	View vv = ApplicationEx.getInstance().history.get(i);
         	if (v.getId() == vv.getId()){
         		ApplicationEx.getInstance().history.remove(i); 
         		break;
         	}
         } 
        	  
        ApplicationEx.getInstance().history.add(v);  
        setContentView(v);  
        
        
        
     }  
   
    
   public void setConfirmAlert(final int keyCode, final KeyEvent event){
	   
	  	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Do you want to exit BigFreakinDeals app?")
				   .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   dialog.cancel(); 
			        	   dialog.dismiss();
			        	   	ApplicationEx.getInstance().isConfirm = true;
			        	   if (event == null)
			        		   onBackPressed();
			        	   else
			        		   onKeyDown(keyCode, event);
			        	   
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			                ApplicationEx.getInstance().isConfirm = false;
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
			
		}
   
   
   @Override    
   public void onBackPressed() {
	   System.out.println("onback pressed of group"+ApplicationEx.getInstance().history.size());
	   
	   		if (ApplicationEx.getInstance().currentTab!=0){
				ApplicationEx.getInstance().currentTab = 0;
				return ;
			}
	   		if (ApplicationEx.getInstance().onDealsDropDown){
	   		 System.out.println("super on back pressed");
	   	  
	   			super.onBackPressed();
	   			return;
	   		}
           if(ApplicationEx.getInstance().history!=null && ApplicationEx.getInstance().history.size() > 1) {  
        	   ApplicationEx.getInstance().history.remove(ApplicationEx.getInstance().history.size()-1);  
               setContentView(ApplicationEx.getInstance().history.get(ApplicationEx.getInstance().history.size()-1)); 
           }else {
           	if (!ApplicationEx.getInstance().isConfirm){
           		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolSlug().
           				compareTo(ApplicationEx.getInstance().myProfile.getHomeUniversity().getSchoolSlug()) == 0) //true
           			{
           			if (ApplicationEx.getInstance().currentTab!=0){
           				ApplicationEx.getInstance().currentTab = 0;
           				return ;
           			}
           			setConfirmAlert(KeyEvent.KEYCODE_BACK,null);  	
                    
           			}else {
           				
           				ApplicationEx.getInstance().myProfile.setlastSelectedSchool(ApplicationEx.getInstance().myProfile.getHomeUniversity());
           				// sethistory
           				ApplicationEx.getInstance().history =new ArrayList<View>();  
           				
           				view = getLocalActivityManager().startActivity("ActiveDeals", new  
                             Intent(this,ActiveDealsActivity.class)  
                            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
                             .getDecorView();  

						// Replace the view of this ActivityGroup  
						replaceView(view);
						
           				
           			}
           	
           	}else {
           	 //  moveTaskToBack(true);
        	  Intent i = new Intent();
        	   i.setAction(Intent.ACTION_MAIN);
        	   i.addCategory(Intent.CATEGORY_HOME);
        	   this.startActivity(i);
        	   /*this is exit clear everything*/
        	   ApplicationEx.getInstance().isConfirm = false;
        	   ApplicationEx.getInstance().myProfile = null;
        	   ApplicationEx.getInstance().schoolListMap = null;
        	   
           	}
           }
       
       return;
   }   
   
   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
	   
      
       if (requestCode != 1) {
               //handle only when startActivityForResult is called
               return;
       }
       
       switch(resultCode) {
       case Activity.RESULT_OK:
               String paykey = data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
               this.paymentSuccessful(paykey);
               break;
       case Activity.RESULT_CANCELED:
               this.paymentCanceled();
               break;
       case PayPalActivity.RESULT_FAILURE:
               String errorID = data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
              
            	  String loginerror = data.getStringExtra(PayPalActivity.LOGIN_FAIL);
              
               
               String errorMessage = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
               this.paymentFailed(errorID, errorMessage+" "+loginerror);
       }
}

   public void setConfirmAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());
		onBackPressed();
		builder.setMessage("Payment is successful. Do you want to view your coupons now?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				dialog.dismiss();
				paypalDone(true);
				
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}

public void paymentSuccessful(String payKey){
	  System.out.println("OnActivityResult = Success"+payKey);
	  	setConfirmAlert();
	 
	  
}

public void paymentCanceled(){
	  System.out.println("OnActivityResult = CANCELLED");
	     
}

public void paymentFailed(String errorID, String errorMessage){
	  System.out.println("OnActivityResult = FAILED"+errorMessage+" "+errorID);
	 
       
}

   
   @Override  
   public boolean onKeyDown(int keyCode, KeyEvent event) {
	   if ((keyCode == KeyEvent.KEYCODE_BACK)) {
		   System.out.println("KEYCODE_BACK ON KYE DOWN"+ApplicationEx.getInstance().history.size());

   			if (ApplicationEx.getInstance().onDealsDropDown){
   				return super.onKeyDown(keyCode, event);
   			
   			}
   			
           if(ApplicationEx.getInstance().history.size() > 1) {  
        	    System.out.println("KEYCODE_BACK step2");
        	    getLocalActivityManager().destroyActivity("FacebookShare", true);
      			ApplicationEx.getInstance().history.remove(ApplicationEx.getInstance().history.size()-1);  
                setContentView(ApplicationEx.getInstance().history.get(ApplicationEx.getInstance().history.size()-1));
                return true;
           }else {
        	   
        	   System.out.println("KEYCODE_BACK step3");
      			
        	   if (!ApplicationEx.getInstance().isConfirm){
              		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolSlug().
              				compareTo(ApplicationEx.getInstance().myProfile.getHomeUniversity().getSchoolSlug()) == 0) //true
              			{
              			if (ApplicationEx.getInstance().currentTab!=0){
               				ApplicationEx.getInstance().currentTab = 0;
               				return true;
               			}
              			setConfirmAlert(KeyEvent.KEYCODE_BACK,null);  	
              			 return true;
              			}else {
              				
              				ApplicationEx.getInstance().myProfile.setlastSelectedSchool(ApplicationEx.getInstance().myProfile.getHomeUniversity());
              				// sethistory
              				ApplicationEx.getInstance().history =new ArrayList<View>();  
              				
              				view = getLocalActivityManager().startActivity("ActiveDeals", new  
                                Intent(this,ActiveDealsActivity.class)  
                               .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
                                .getDecorView();  

   						// Replace the view of this ActivityGroup  
   						replaceView(view);
   						
   					 return true;
              			}
              	
              	}else {
              		 System.out.println("KEYCODE_BACK step4");
              /* 		
           	   Intent i = new Intent();
        	   i.setAction(Intent.ACTION_MAIN);
        	   i.addCategory(Intent.CATEGORY_HOME);
        	   this.startActivity(i);*/
               finish();
        	   /*this is exit clear everything*/
        	   ApplicationEx.getInstance().isConfirm = false;
        	   ApplicationEx.getInstance().myProfile = null;
        	   ApplicationEx.getInstance().schoolListMap = null;
        	   return true;
           	}
          }
          
       }
       return super.onKeyDown(keyCode, event);
   }
  

    
 }  
